﻿// Xshell Command - Launch Application
// 
// <copyright file="LaunchApplicationCommand.cs" company="TaskyMedia LLC">
//   Copyright © 2010 TaskyMedia LLC
// </copyright>

namespace Xshell.Commands
{
    using System;
    using System.Diagnostics;
    using System.IO;

    /// <summary>
    /// Launches an application.
    /// </summary>
    [XsCommand("LaunchApplication", typeof(LaunchApplicationCommandArgs))]
    internal class LaunchApplicationCommand : IXsCommand
    {
        /// <summary>
        /// Executes the command with the specified arguments.
        /// </summary>
        /// <param name="args">The command arguments.</param>
        public void ExecuteCommand(IXsCommandArgs args)
        {
            // Validate the arguments
            if (args == null)
            {
                throw new InvalidOperationException("Command arguments are required for this operation");
            }

            if (!(args is LaunchApplicationCommandArgs))
            {
                throw new InvalidOperationException("Invalid command argument container type");
            }

            LaunchApplicationCommandArgs launchArgs = (LaunchApplicationCommandArgs)args;
            if (String.IsNullOrEmpty(launchArgs.Path))
            {
                throw new InvalidOperationException("Path is a required argument");
            }

            ProcessStartInfo processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = launchArgs.Path;
            processStartInfo.WindowStyle = ProcessWindowStyle.Normal;

            if (!File.Exists(launchArgs.Path))
            {
                processStartInfo.UseShellExecute = true;
            }

            if (!String.IsNullOrEmpty(launchArgs.CommandLineArgs))
            {
                processStartInfo.Arguments = launchArgs.CommandLineArgs;
            }

            Process process = Process.Start(processStartInfo);

            if (!String.IsNullOrEmpty(launchArgs.WaitForExit))
            {
                if (launchArgs.WaitForExit.ToLowerInvariant() == "true" || launchArgs.WaitForExit == "1")
                {
                    process.WaitForExit();
                }
            }
        }
    }
}
